import redis
import os
from utili import IniConfig
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATABASE_CONF_FILE = os.path.join(BASE_DIR, 'configs\database_configs.ini')


# 不适用于模糊搜索
class RedisHandler:
    def __init__(self, host, port, password):
        pools = redis.ConnectionPool(host=host, port=port, password=password, decode_responses=True)
        self.__redis = redis.StrictRedis(connection_pool=pools)

    # 选择redis数据库，redis默认16个数据库
    def selectDb(self, dbId):
        return self.__redis.select(dbId)

    # 在 Redis 中设置值，默认，不存在则创建，存在则修改。
    def set(self, key, value):
        return self.__redis.set(key, value)

    # 取出键对应的值
    def get(self, key):
        if self.__redis.exists(key):
            return self.__redis.get(key)
        else:
            return None

    # 获取有序集合中所有元素
    def zrange(self, key):
        if self.__redis.exists(key):
            return self.__redis.zrange(key, 0, -1, desc=False, withscores=True)
        else:
            return None

    # 获取值的索引号
    def zrank(self, key):
        if self.__redis.exists(key):
            return self.__redis.zrank(key)
        else:
            return None

    # 按照分数范围获取name对应的有序集合的元素
    def zrangebyscore(self, key):
        if self.__redis.exists(key):
            return self.__redis.zrangebyscore(key, 0, -1, withscores=True)
        else:
            return None

    # 按照分数范围获取有序集合的元素并排序（默认从大到小排序）
    def zrevrange(self, key):
        if self.__redis.exists(key):
            return self.__redis.zrevrange(key, 0, -1)
        else:
            return None

    # 删除键值对
    def delete(self, key):
        if self.__redis.exists(key):
            return self.__redis.delete(key)
        else:
            return None

    # 获取key对应hash的所有键值
    def hgetall(self, key):
        if self.__redis.exists(key):
            return self.__redis.hgetall(key)
        else:
            return None

    # 统计返回的总个数
    def rcount(self, re, key):
        if self.__redis.exists(key):
            sum = 0
            for i in re:
                print(i)
                sum += 1
            print("总共有%s个" % (sum))


if __name__ == "__main__":
    iniConfig = IniConfig.IniCfg()
    sections = iniConfig.readSectionItems(DATABASE_CONF_FILE)
    MyR = RedisHandler(iniConfig.prettySecToDic("redis_server").get("host"),int(iniConfig.prettySecToDic("redis_server").get("port")),iniConfig.prettySecToDic("redis_server").get("password"))
    MyR.selectDb(5)
    key = "menu:list:level:0"
    print(MyR.get(key))
    # re = MyR.zrange(key)
    # print(re)
    # print(MyR.get('menu'))
    # print(MyR.zrange('menu'))
    # MyR.rcount(re, key)
    # print(MyR.rcount(re, key))
